package com.cloud.common.utils;

import java.sql.*;

/**
 * @author gyj
 * @version 1.0
 * @date 2020/11/23 16:11
 */
public class DBUtil {
    private static final String DRIVER = "com.mysql.cj.jdbc.Driver";
    public static final String URL = "jdbc:mysql://192.168.9.171:3306/cloud_user?autoReconnect=true&useSSL=false&useUnicode=true&characterEncoding=utf-8&serverTimezone=Asia/Shanghai";
    public static final String USER = "root";
    public static final String PASSWORD = "91MySQL_171";

    private DBUtil() {
    }

    static {
        try {
            //1.注册驱动 静态代码块DriverManager.registerDriver(new Driver());
            Class.forName(DRIVER);
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        }
    }

    public static Connection getConn() throws SQLException {
        //2.开启连接通道
        return DriverManager.getConnection(URL, USER, PASSWORD);
    }

    /**
     * 处理事务
     * conn.setAutoCommit(false);
     * conn.commit();
     * conn.rollback();
     */
    public static void close(Connection conn, Statement ps, ResultSet rs) {
        //6.关闭连接
        if (rs != null) {
            try {
                rs.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }
        if (ps != null) {
            try {
                ps.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }
        if (conn != null) {
            try {
                conn.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }
    }
}
